package com.xuecheng.order.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.order.config.PayTemplate;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mapper.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-13
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {
   @Autowired
   private OrdersService ordersService;
   @Autowired
   private PayTemplate payTemplate;
    //接收订单编号生成支付链接
    @Override
    public ResponseResult<String> creatPay(String orderNo) {
        //通过订单号查询订单
        LambdaQueryWrapper<Orders> lq = new LambdaQueryWrapper<>();
        lq.eq(Orders::getOrderNo,orderNo);
        Orders orders = ordersService.getOne(lq);
        //校验订单状态 初始状态为未支付
        if (!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //查询支付明细
        Payment payment = this.lambdaQuery()
                .eq(Payment::getOrderNo, orderNo)
                .one();
        //判断是否已生成支付明细对象
        //如果已经有支付对象 将支付对象的链接返回
        if (payment!=null) {
            return ResponseResult.okResult(payment.getPayResponse());
        }else{
            //没有支付对象信息、生成一个支付对象返回支付链接
            // 调用微信工具类生成支付连接 // 教学环境，支付环境写死为1分钱
            String payUrl = payTemplate.createOrder(orders.getOrderNo(), 1L, orders.getCoursePubName());
            // 封装并保存订单明细
            payment = new Payment();
            payment.setUserId(orders.getUserId());// 用户id
            payment.setCompanyId(orders.getCompanyId()); // 课程机构id
            payment.setOrderNo(orderNo);// 订单号
            payment.setStatus("0"); // 交易状态：未支付
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX); // 支付方式
            payment.setTotalAmount(orders.getPrice());// 订单金额
            payment.setCreateDate(new Date()); // 创建时间
            payment.setPayResponse(payUrl);// 支付连接
            this.save(payment);
            // 返回支付链接
            return ResponseResult.okResult(payUrl);

        }
    }
}
